#include "head.h"


void* start_routine(void* arg)
{
    pool_t* pool = (pool_t*)arg;

    MYSQL* mysql = malloc(sizeof(MYSQL));
    pthread_mutex_lock(&pool->mutex);
    MysqlInit(mysql);
    ERROR_CHECK(mysql, NULL, "MysqlInit");
    pthread_mutex_unlock(&pool->mutex);

    while(1)
    {
        pthread_mutex_lock(&pool->mutex);
        
        while(pool->q->size == 0 && pool->alive == true)
            pthread_cond_wait(&pool->cond, &pool->mutex);

        if(pool->alive == false)
        {
            pthread_mutex_unlock(&pool->mutex);
            pthread_exit(NULL);
        }
            
        node_t * node = pop_queue(pool->q);

        pthread_mutex_unlock(&pool->mutex);

        work(node, mysql);
        printf("工作结束\n");
        free(node);
    }

    free(mysql);
    return NULL;
}


pool_t* create_pool(void)
{
    pool_t* pool = malloc(sizeof(pool_t));
    if(pool == NULL)
        error(1, errno, "malloc");

    pool->q = creat_queue();

    pthread_mutex_init(&pool->mutex, NULL);
    pthread_cond_init(&pool->cond, NULL);

    pool->alive = true;

    for(int i = 0; i < POOL_NUM; ++i)
        pthread_create(pool->thread_pid + i, NULL, start_routine, pool);
    
    for(int i = 0; i < POOL_NUM; ++i)
        printf("pthread_pid = %ld\n", pool->thread_pid[i]);
    printf("线程池已建立\n");
    return pool;
}

int destory_pool(pool_t* pool)
{
    destroy_queue(pool->q);
    free(pool);
}


int work(node_t* node, MYSQL* mysql)
{
    printf("work\n");
    cmd_t cmd = node->msg.cmd;
    printf("cmd = %d\n", cmd);
    switch(cmd)
    {
    //case LS: to_ls(&node->msg, node->val, mysql);  break;
    case UP: to_up(&node->msg, node->val, mysql);  break;
    //case RM: to_rm(&node->msg, node->val, mysql);  break;
    }

    return 0;
}


